package com.wish.wishfinancial_service.service.impl;

import com.alibaba.fastjson.JSON;
import com.wish.wishfinancial_service.entity.TCwPaymentPlan;
import com.wish.wishfinancial_service.entity.TJrProduct;
import com.wish.wishfinancial_service.entity.TJrSfLoan;
import com.wish.wishfinancial_service.entity.TSfContract;
import com.wish.wishfinancial_service.enums.*;
import com.wish.wishfinancial_service.mapper.*;
import com.wish.wishfinancial_service.service.ITJrSfLoanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.wishfinancial_service.service.feignservice.HouseServiceFeign;
import dto.financialResponse.SearchSfLoanDetailMiniResponseDto;
import dto.financialResponse.SearchSfLoanDetailsResponseDto;
import dto.financialservice.SaveSfLoanRequestDto;
import dto.financialservice.SearchSfLoanDetailRequestDto;
import enums.BusinessCostTypesEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utils.MyJinRongUtils;
import utils.SerialType;

import java.util.*;

/**
 * <p>
 * 收房贷申请信息 服务实现类
 * </p>
 *
 * @author weijiaz
 * @since 2021-04-10
 */
@Service
@Slf4j
public class TJrSfLoanServiceImpl extends ServiceImpl<TJrSfLoanMapper, TJrSfLoan> implements ITJrSfLoanService {

    @Autowired
    private TJrProductMapper tJrProductMapper;
    @Autowired
    private TSfContractMapper tSfContractMapper;
    @Autowired
    private TCwPaymentPlanMapper tCwPaymentPlanMapper;
    @Autowired
    private TMSequenceMapper tmSequenceMapper;

    @Autowired
    private HouseServiceFeign houseServiceFeign;
    @Override
    public SearchSfLoanDetailsResponseDto getSfLoanDetail(SearchSfLoanDetailRequestDto sfdto) {
        log.info("getSfLoanDetail收房贷计算分期信息处理Start...");
        log.info("----收房贷计算分期入参：{}", JSON.toJSONString(sfdto));
        SearchSfLoanDetailsResponseDto dto = new SearchSfLoanDetailsResponseDto();
        List<SearchSfLoanDetailMiniResponseDto> spList = new ArrayList<SearchSfLoanDetailMiniResponseDto>();
        TJrProduct product = tJrProductMapper.selectById(sfdto.getProductId());
        //授信率
        Double creditLine = MyJinRongUtils.div(product.getCreditLine(), 100, 2);
        //一次性服务费
        double serviceFee = MyJinRongUtils.div(Double.parseDouble(sfdto.getServiceFee()), 100, 4);
        //利率
        double rate = MyJinRongUtils.div(Double.parseDouble(sfdto.getRate()), 100, 4);// 利率

        //授信额合计
        double sxBalance = MyJinRongUtils.mul(sfdto.getBalance(), creditLine);

        // 合同期数
        Long sfperiod = sfdto.getPeriods();
        int sfperiods=sfperiod.intValue();

        //服务费合计=   (借款金额*一次性服务费 /12 * 期数 * 授信额)
        double ser_Charge=MyJinRongUtils.mul(sfdto.getBalance(), serviceFee);
        double ser_Charge_ = MyJinRongUtils.div(ser_Charge, 12, 2);
        double _ser_Charge=MyJinRongUtils.mul(ser_Charge_, sfperiods);
        double serCharge=MyJinRongUtils.mul(_ser_Charge, creditLine);

        // 计算 月租金
        double month_RateAmount=MyJinRongUtils.div(sfdto.getBalance(),sfperiods,2);
        // 借款总额(应付租约合计 )   = 月租金* 期数 * 授信
        double monthAmount = MyJinRongUtils.mul(month_RateAmount, sfperiods);
        double payAbleCount_ = MyJinRongUtils.mul(monthAmount,creditLine);

        // 计算收房贷利息合计= 借款金额* 利率/12  * 授信额 * 期数
        //借款金额* 利率
        double rates= MyJinRongUtils.mul(payAbleCount_, rate);
        // 利率/12
        double  monthRateAmounts_=MyJinRongUtils.div(rates,12,2);
        double  monthRateAmounts=MyJinRongUtils.mul(monthRateAmounts_,sfperiods);

        //利息合计 InterestCount
        double InterestCount=0;
        //还款总额合计      (账期还款金额的合计)
        double rePaymentCount=0;
        //应付租约合计      (总金额)
        double payAbleCount=payAbleCount_;
        // 根据一段时间区间，按月份拆分成多个时间段
        List<MyJinRongUtils.KeyValueForDate> splitMonth = MyJinRongUtils.getSplitMonthForDate(sfdto.getStartDate(), sfdto.getEndDate());
        //收房合同
        TSfContract sfentity = tSfContractMapper.selectById(sfdto.getContractId());
        int no=1;

        SearchSfLoanDetailMiniResponseDto sfdmini=null;
        // 账期利息 （每月利息）= 利息总和/ 期数
        double  rateAmount=MyJinRongUtils.div(monthRateAmounts,sfperiods,2);
        //计算月租金
        // 账期还款金额（每月账期还款金）= 还款总额合计 / 期数
        double repaymentAmount_=MyJinRongUtils.div(payAbleCount,sfperiods,2);
        double repaymentAmount = MyJinRongUtils.add(repaymentAmount_, rateAmount);
        //利息合计
        InterestCount=MyJinRongUtils.add(InterestCount, monthRateAmounts);
        // 还款总额合计  = 账期还款金额（每月账期还款金）* 期数
        rePaymentCount=MyJinRongUtils.mul(repaymentAmount,sfperiods);
        // 循环计算分期详情列表
        for (MyJinRongUtils.KeyValueForDate v : splitMonth) {
            sfdmini=new SearchSfLoanDetailMiniResponseDto();
            sfdmini.setNo(no);
            // 房产编号
            sfdmini.setRoomCode(sfentity.getHouseId());
            // 房产信息 = 小区名+房产信息
            sfdmini.setRealEstateInfo(sfentity.getPremiseName()+sfentity.getHouseName());
            // 利息
            sfdmini.setMonthRateAmount(rateAmount);
            // 月租金
            sfdmini.setMonthRepaymentAmount(repaymentAmount);
            // 合同开始日
            sfdmini.setStarLoanday(v.getStartDate());
            // 合同结束日
            sfdmini.setEndLoanday(v.getEndDate());
            spList.add(sfdmini);
            no++;
        }
        dto.setPayAbleCount(payAbleCount + "");// 应付租约合计
        dto.setRePaymentCount(rePaymentCount + "");// 还款总额合计
        dto.setInterestCount(InterestCount + "");// 收房贷利息合计
        dto.setSerCharge(serCharge + "");// 一次性服务费
        dto.setProductId(product.getId());//产品id
        dto.setSxAbleCount(sxBalance + "");
        dto.setSfLoan(spList);
        dto.setId(sfdto.getContractId());//合同id

        dto.setServiceFee(sfdto.getServiceFee());//一次性服务费率
        dto.setRate(sfdto.getRate());//利率

        log.info("getSfLoanDetail收房贷计算分期信息处理end...");
        return dto;
    }

    @Override
    public void saveLoan(SaveSfLoanRequestDto sfdto)  {
        log.info("saveLoan保存(收房贷申请)处理Start...");
        log.info("----保存(收房贷申请)入参：{}",JSON.toJSONString(sfdto));
        //保存收房贷申请
        TJrSfLoan jrse = new TJrSfLoan();
        jrse.setBusinessId(sfdto.getBusinessId());
        jrse.setDeptId(sfdto.getDeptId());
        jrse.setDeptNo(sfdto.getDeptNo());
        jrse.setSfContractId(sfdto.getId());
        jrse.setLoanAmount(sfdto.getSxBalance());
        jrse.setMonthLimit(sfdto.getPeriods());
        jrse.setRate(sfdto.getRate());
        jrse.setServiceFee(sfdto.getServiceFee());
        jrse.setJrProductId(sfdto.getProductId());
        jrse.setReLeaseCount(sfdto.getPayAbleCount());
        jrse.setRpAmountCount(sfdto.getRePaymentCount());
        jrse.setSerCharge(sfdto.getSerCharge());
        jrse.setAgInterestRate(sfdto.getInterestCount());
        jrse.setApplyState(FinanceApplyStateEnum.SHZ.getIndex());
        jrse.setRemark(sfdto.getRemarks());
        jrse.setCreateUserid(sfdto.getLoginUserId());
        jrse.setCreateTime(new Date());
        jrse.setUpdateUserid(sfdto.getLoginUserId());
        jrse.setUpdateTime(new Date());
        jrse.setDelFlg(0);

        String sfLoanOrderNo="";
        try {
            sfLoanOrderNo = this.houseServiceFeign.getSerialNumber(SerialType.SHOUFANGDAISQ);
        } catch (Exception e) {
            log.error("收房贷申请单号编号生成失败。", e);
            e.printStackTrace();
        }
        jrse.setSfLoanOrderNo(sfLoanOrderNo);

        baseMapper.insert(jrse);
        //更新收房合同表
        TSfContract sfContract = tSfContractMapper.selectById(sfdto.getId());
        //*sfContract.setSfLoanFlg(true);*//**//*(审核通过之后更新这个)*//*
        sfContract.setFreezeStatus(FreezeStatusEnum.YDJ.getIndex());
        sfContract.setUpdateUserid(sfdto.getLoginUserId());
        sfContract.setUpdateTime(new Date());
        tSfContractMapper.updateById(sfContract);
        //更新付款计划表
        List<TCwPaymentPlan> cwPaymentList = this.getCwPaymentList(sfdto.getId());
        for (TCwPaymentPlan cpl : cwPaymentList) {
            cpl.setPayState(PayStatusEnum.YDJ.getIndex());
            cpl.setUpdateUserid(sfdto.getLoginUserId());
            cpl.setUpdateTime(new Date());
            tCwPaymentPlanMapper.updateById(cpl);
        }
        log.info("saveLoan保存(收房贷申请)处理End...");
    }

    // 查询 - 付款计划（未付款）
    private List<TCwPaymentPlan> getCwPaymentList(Long sfid) {
        Map<String, Object> param = new HashMap<>();
        param.put("contract_type", ContractTypeEnum.SF.getIndex());
        param.put("contract_id",sfid);
        param.put("pay_type", PaymentTypeEnum.SFFK.getIndex());
        param.put("pay_state",PayStatusEnum.WFK.getIndex());
        param.put("bill_type",PayPlanZdType.PTZD.getIndex());
        param.put("item_type", BusinessCostTypesEnum.ZUJIN.getIndex());
        return tCwPaymentPlanMapper.selectByMap(param);

    }
}
